package cn.windy.samary.module.admin.controller;

import cn.windy.samary.core.annotation.OpLog;
import cn.windy.samary.module.abstracts.controller.AbstractController;
import cn.windy.samary.module.admin.common.UserLine;
import cn.windy.samary.module.admin.entity.Role;
import cn.windy.samary.module.admin.entity.User;
import cn.windy.samary.module.admin.entity.UserRole;
import cn.windy.samary.module.admin.service.IRoleService;
import cn.windy.samary.module.admin.service.IUserRoleService;
import cn.windy.samary.module.admin.service.IUserService;
import cn.windy.samary.utils.PageContent;
import cn.windy.samary.utils.Res;
import cn.windy.samary.utils.ShiroUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyl
 * @date 2018/5/21 15:24
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController extends AbstractController {

    private String prefix = "admin/role/";

    @Resource
    private IRoleService roleService;
    @Resource
    private IUserService userService;
    @Resource
    private IUserRoleService userRoleService;

    @GetMapping
    @OpLog(value = "打开角色管理界面")
    @RequiresPermissions("admin:role:role")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("basePath", getBasePath(request));
        return prefix + "role";
    }

    @ResponseBody
    @GetMapping(value = "/list")
    @OpLog(value = "查询角色列表")
    @RequiresPermissions("admin:role:role")
    public Object list(PageContent pageContent) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        UserLine userLine = ShiroUtils.getUserLine();
        if (!"0001".equals(userLine.getId())) {
            criteria.andNotEqualTo("id", "0001");
        }
        Page<Object> page = PageHelper.offsetPage(pageContent.getOffset(), pageContent.getLimit(), true);
        List<Role> roles = roleService.selectByExample(example);
        return Res.rows(roles, page.getTotal());
    }

    @OpLog("添加角色")
    @GetMapping("add")
    @RequiresPermissions("admin:role:add")
    public String add(HttpServletRequest request, Model model) {
        model.addAttribute("basePath", getBasePath(request));
        return prefix + "roleAdd";
    }

    @OpLog("编辑角色")
    @GetMapping("edit/{id}")
    @RequiresPermissions("admin:role:edit")
    public String edit(HttpServletRequest request, Model model,
                       @PathVariable String id) {
        model.addAttribute("basePath", getBasePath(request));
        Role role = roleService.selectByPrimaryKey(id);
        model.addAttribute("role", role);
        return prefix + "roleEdit";
    }

    @ResponseBody
    @OpLog("保存角色")
    @PostMapping("save")
    @RequiresPermissions("admin:role:add")
    public Object save(@Valid Role entity, String menuIds) {
        int i = roleService.save(entity, menuIds);
        return i != 0 ? Res.ok() : Res.error();
    }

    @ResponseBody
    @OpLog("更新角色")
    @PutMapping("update")
    @RequiresPermissions("admin:role:edit")
    public Object update(@Valid Role entity, String menuIds) {
        int i = roleService.update(entity, menuIds);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("删除角色")
    @ResponseBody
    @DeleteMapping("remove")
    @RequiresPermissions("admin:role:remove")
    public Object remove(String id) {
        if ("0001".equals(id) || "0002".equals(id)) {
            return Res.ok("内置角色无法删除！");
        }
        int i = roleService.deleteById(id);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("批量删除角色")
    @ResponseBody
    @DeleteMapping("batchRemove")
    @RequiresPermissions("admin:role:batchRemove")
    public Object batchRemove(@RequestParam(value = "ids[]") String[] ids) {
        List<String> idsList = new ArrayList<>();
        for (String id : ids) {
            if (!"0001".equals(id) && !"0002".equals(id)) {
                idsList.add(id);
            }
        }
        if (idsList.size() != 0) {
            roleService.deleteByIdIn(idsList);
        }
        return ids.length == idsList.size() ? Res.ok() : Res.ok();
    }


    /**
     * 查询所有可用角色,当用户id数组长度为1时，同时返回该用户所拥有的角色，其他时候返回空集合
     *
     * @param userIds 用户id数组
     * @return 所有可用角色，和用户已有角色（仅当用户id数组长度为1时）
     */
    @ResponseBody
    @GetMapping(value = "/getAllRole")
    @OpLog(value = "查询所有可用角色")
    public Object getAllRole(@RequestParam(value = "userIds[]", required = false) String[] userIds) {
        UserLine userLine = ShiroUtils.getUserLine();
        List<Role> roleList = roleService.selectAll();
        if (!"0001".equals(userLine.getId())) {
            roleList.removeIf(next -> "0001".equals(next.getId()));
        }
        JSONObject object = new JSONObject();
        JSONArray array = new JSONArray();
        JSONArray array2 = new JSONArray();
        array.addAll(roleList);
        object.put("allRole", array);
        if (userIds != null && userIds.length == 1) {
            User user = userService.selectByPrimaryKey(userIds[0]);
            if (user != null) {
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                List<UserRole> select = userRoleService.select(userRole);
                for (UserRole role : select) {
                    array2.add(role.getRoleId());
                }
            }
        }
        object.put("userRole", array2);
        return object;
    }
}
